package com.grq.mis.util;

import cn.hutool.core.lang.Validator;
import com.grq.mis.exception.BusinessException;
import com.grq.mis.exception.ResultEnum;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

public class FhtUtil {

    public static final List<String> DEFAULT_IMG_SUFFIX = Arrays.asList(new String[]{"jpg", "jpeg", "png", "bmp", "gif"});

    public static String getFileSuffix(MultipartFile file) {
        if (file == null){
            return "";
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
        return suffix;
    }

    // 检查是否为图片文件
    public static void checkImgFile(MultipartFile file) {

        // 判断文件是否存在
        if (file == null || Validator.isEmpty(file.getOriginalFilename())) {
            throw new BusinessException(ResultEnum.UPLOAD_FILE_ERROR, "请上传图片");
        }
        // 判断文件类型
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
        if (!DEFAULT_IMG_SUFFIX.contains(suffix)) {
            throw new BusinessException(ResultEnum.UPLOAD_FILE_ERROR, "文件格式错误,只支持jpg, jpeg, png, bmp, gif");
        }
        // 判断文件大小
        long maxFileSize = 5 * 1024 * 1024;
        if (file.getSize() > maxFileSize) {
            throw new BusinessException(ResultEnum.UPLOAD_FILE_ERROR, "上传图片不能大于5M");
        }
    }

}
